<template>
  <ProTable
    ref="tableRef"
    :fetchListApi="_listLevelWarm"
    :columns="columns"
    row-key="name"
    hidePagination
    :rowSelection="rowSelection"
  >
    <template #expandIcon="{ expanded, onExpand, record }">
      <DownOutlined
        :rotate="expanded ? 0 : -90"
        @Click="
          (e) => {
            onExpand(record, e);
          }
        "
      />
    </template>
    <template #toolbars>
      <Space>
        <b-button icon="add" @click="onAdd()" code="levelConfig:add"
          >新增</b-button
        >
        <b-button
          icon="delete"
          @click="onDelete()"
          :disabled="!selectedRowKeys.length"
          code="levelConfig:remove"
          >删除</b-button
        >
      </Space>
    </template>
    <template #expandedRowRender="{ record }">
      <ProTable
        :columns="expandedColumns"
        row-key="id"
        hide-search
        :height="310"
        hidePagination
        hideTableOptions
        :fetch-list-api="async () => ({ rows: record.levelConfigVOList })"
      >
        <template #intensity="{ record }">
          <Space>
            <Tag
              v-for="(item, index) in record.intensity"
              :key="index"
              :color="colorEnu[record.level as keyof typeof colorEnu]"
              style="color: #0c0c0c"
              >{{ item }}
            </Tag>
          </Space>
        </template>
      </ProTable>
    </template>
    <template #operation="{ record }">
      <b-button
        icon="edit"
        type="link"
        @click="onView(record)"
        code="levelConfig:query"
        >详情</b-button
      >
    </template>
  </ProTable>
  <FormModal :items="items"> </FormModal>
</template>

<script setup lang="tsx">
import { computed, ref } from 'vue';
import { hasPermission } from '@/permission';
import { DownOutlined } from '@ant-design/icons-vue';
import { Modal, Space, Tag, message } from 'ant-design-vue';
import { cloneDeep } from 'lodash-es';
import { ProFormProps } from '@/components/ProForm';
import { ProTable, ProTableProps } from '@/components/ProTable/index';
import { useFormModal } from '@/hooks/formModal';
import {
  addWarm,
  deleteWarm,
  getProvinceList,
  listLevelWarm,
  updateWarm,
} from '@/api/config';

const selectedRowKeys = ref<any[]>([]);
const rowSelection = computed<ProTableProps['rowSelection']>(() => {
  return {
    selectedRowKeys: selectedRowKeys.value,
    onChange(values, all) {
      selectedRowKeys.value = values as number[];
    },
  };
});
const defaultFlagEnum = {
  '1': '默认',
  '0': '非默认',
};
const colorEnu = {
  无预警: '#808080',
  Ⅳ级: '#409EFF',
  Ⅲ级: '#ffff00',
  Ⅱ级: '#ffa500',
  Ⅰ级: '#ff0000',
};
const levelOption = [...Array(12)].map((_, i) => ({ value: i + 1 }));
const tableRef = ref();
const _listLevelWarm = async (params: any) => {
  const res = await listLevelWarm(params);
  res.rows.forEach((item: any, index: any) => {
    item.levelConfigVOList.forEach((list: any) => {
      if (list.intensity) {
        list.intensity = list.intensity.split(',').map(Number);
      } else {
        list.intensity = [];
      }
    });
  });
  return res;
};
const provinceListOption = ref<Global.Option[]>([]);
const init = async () => {
  const res: any = await getProvinceList();
  provinceListOption.value = res.data.map((i: any) => ({ value: i }));
};
init();

const columns = computed<ProTableProps['columns']>(() => [
  {
    title: '名称',
    dataIndex: 'name',
  },
  {
    title: '省份',
    dataIndex: 'province',
    hideInSearch: true,
  },
  {
    title: '是否默认配置',
    dataIndex: 'defaultFlag',
    hideInSearch: true,
    customRender({ text }) {
      return (
        <Tag color={text == '1' ? 'success' : 'error'}>
          {defaultFlagEnum?.[text as keyof typeof defaultFlagEnum]}
        </Tag>
      );
    },
  },
  {
    title: '操作',
    dataIndex: 'operation',
    hideInSearch: true,
    fixed: 'right',
    width: 80,
  },
]);
const expandedColumns = computed<ProTableProps['columns']>(() => [
  {
    title: '烈度范围',
    dataIndex: 'intensity',
    width: 300,
  },
  {
    title: '预警等级',
    dataIndex: 'level',
  },
  {
    title: '等级颜色',
    dataIndex: 'levelColor',
  },
  {
    title: '避震指导',
    dataIndex: 'guidance',
  },
]);

const validator = (rule: any, value: any, callback: any) => {
  if (value) {
    for (let j = 1; j < value.length; j++) {
      if (value[j] != value[j - 1] + 1) {
        return Promise.reject('不连续');
      }
    }
  }
  return Promise.resolve();
};
const removeRepeat = (rawArr: any, removeArr: any) => {
  let raw = new Set([...rawArr]);
  for (let i of removeArr) {
    raw.delete(i);
  }
  return [...raw];
};
const items = computed<ProFormProps['items']>(() => [
  {
    label: '配置名称',
    type: 'input',
    field: 'name',
    rules: [
      {
        required: true,
        message: '请输入配置名称',
        trigger: 'blur',
      },
    ],
    props: {
      placeholder: '请输入配置名称',
    },
  },
  {
    label: '无预警列度范围',
    type: 'select',
    field: ['levelConfigVOList', 0, 'intensity'],
    rules: [
      {
        required: false,
        message: '所选等级必须连续，不可跳选',
        validator,
        trigger: 'change',
      },
    ],
    props: {
      placeholder: '请选择无预警列度范围',
      mode: 'multiple',
      options: levelOption,
      showArrow: true,
      onChange(value: any, option) {
        openData.value.levelConfigVOList.forEach((item: any, index: any) => {
          if (index != 0) {
            item.intensity = removeRepeat(item.intensity, value);
          } else {
            openData.value.levelConfigVOList[0].intensity = value.sort(
              (a: any, b: any) => {
                return a - b;
              },
            );
          }
        });
      },
      style: { '--alertLevel': 'grey', color: '#0c0c0c' },
    },
  },
  {
    label: '蓝色预警列度范围',
    type: 'select',
    field: ['levelConfigVOList', 1, 'intensity'],
    rules: [
      {
        required: false,
        message: '所选等级必须连续，不可跳选',
        validator,
        trigger: 'change',
      },
    ],
    props: {
      placeholder: '请选择蓝色预警列度范围',
      mode: 'multiple',
      options: levelOption,
      showArrow: true,
      onChange(value: any, option) {
        openData.value.levelConfigVOList.forEach((item: any, index: any) => {
          if (index != 1) {
            item.intensity = removeRepeat(item.intensity, value);
          } else {
            openData.value.levelConfigVOList[1].intensity = value.sort(
              (a: any, b: any) => {
                return a - b;
              },
            );
          }
        });
      },
      style: { '--alertLevel': '#409EFF', color: '#0c0c0c' },
    },
  },
  {
    label: '黄色预警列度范围',
    type: 'select',
    field: ['levelConfigVOList', 2, 'intensity'],
    rules: [
      {
        message: '所选等级必须连续，不可跳选',
        validator,
        trigger: 'change',
      },
    ],
    props: {
      placeholder: '请选择黄色预警列度范围',
      mode: 'multiple',
      options: levelOption,
      showArrow: true,
      onChange(value: any, option) {
        openData.value.levelConfigVOList.forEach((item: any, index: any) => {
          if (index != 2) {
            item.intensity = removeRepeat(item.intensity, value);
          } else {
            openData.value.levelConfigVOList[2].intensity = value.sort(
              (a: any, b: any) => {
                return a - b;
              },
            );
          }
        });
      },
      style: { '--alertLevel': 'yellow', color: '#0c0c0c' },
    },
  },
  {
    label: '橙色预警列度范围',
    type: 'select',
    field: ['levelConfigVOList', 3, 'intensity'],
    rules: [
      {
        message: '所选等级必须连续，不可跳选',
        validator,
        trigger: 'change',
      },
    ],
    props: {
      placeholder: '请选择橙色预警列度范围',
      mode: 'multiple',
      options: levelOption,
      showArrow: true,
      onChange(value: any, option) {
        openData.value.levelConfigVOList.forEach((item: any, index: any) => {
          if (index != 3) {
            item.intensity = removeRepeat(item.intensity, value);
          } else {
            openData.value.levelConfigVOList[3].intensity = value.sort(
              (a: any, b: any) => {
                return a - b;
              },
            );
          }
        });
      },
      style: { '--alertLevel': 'orange', color: '#0c0c0c' },
    },
  },
  {
    label: '红色预警列度范围',
    type: 'select',
    field: ['levelConfigVOList', 4, 'intensity'],
    rules: [
      {
        message: '所选等级必须连续，不可跳选',
        validator,
        trigger: 'change',
      },
    ],
    props: {
      placeholder: '请选择红色预警列度范围',
      mode: 'multiple',
      options: levelOption,
      showArrow: true,
      onChange(value: any, option) {
        openData.value.levelConfigVOList.forEach((item: any, index: any) => {
          if (index != 4) {
            item.intensity = removeRepeat(item.intensity, value);
          } else {
            openData.value.levelConfigVOList[4].intensity = value.sort(
              (a: any, b: any) => {
                return a - b;
              },
            );
          }
        });
      },
      style: { '--alertLevel': 'red', color: '#0c0c0c' },
    },
  },
  {
    label: '默认配置',
    type: 'switch',
    field: 'defaultFlag',
    rules: [
      {
        required: true,
        message: '请选择是否为默认配置',
        trigger: 'change',
      },
    ],
    props: {
      unCheckedValue: '0',
      unCheckedChildren: '否',
      checkedValue: '1',
      checkedChildren: '是',
    },
  },
  {
    label: '省份',
    type: 'select',
    field: 'province',
    rules: [
      {
        required: true,
        message: '请选择省份',
        trigger: 'blur',
      },
    ],
    props: {
      placeholder: '请选择省份',
      options: provinceListOption.value,
    },
  },
]);
const { FormModal, open } = useFormModal({
  size: 'small',
  column: 1,
  formProps: { labelCol: { span: 5 } },
});
const levelConfigVOListTemplate = () => [
  {
    intensity: [1, 2],
    level: '无预警',
    levelColor: '无预警（灰色）',
    guidance: '此次地震无影响',
  },
  {
    intensity: [3, 4, 5],
    level: 'Ⅳ级',
    levelColor: '蓝色预警',
    guidance: '有感地震，注意观察',
  },
  {
    intensity: [6, 7, 8],
    level: 'Ⅲ级',
    levelColor: '黄色预警',
    guidance: '有感地震，注意防范',
  },
  {
    intensity: [9, 10],
    level: 'Ⅱ级',
    levelColor: '橙色预警',
    guidance: '强烈地震，立即避险',
  },
  {
    intensity: [11, 12],
    level: 'Ⅰ级',
    levelColor: '红色预警',
    guidance: '破坏地震，紧急避险',
  },
];

const openData: any = ref({});
const strAll = [...Array(12).keys()].map((i) => i + 1).join();
const onAdd = () => {
  openData.value = {
    levelConfigVOList: levelConfigVOListTemplate(),
    defaultFlag: '0',
  };
  open({
    title: '新增',
    defaultValue: openData.value,
    serviceApi: async (params: any): Promise<any> => {
      let arr: any = [];
      const levelConfigDTOList = cloneDeep(params.levelConfigVOList);
      levelConfigDTOList.forEach((list: any) => {
        arr = arr.concat(list.intensity);
        list.intensity = list.intensity?.join() || '';
      });
      if (arr.join() != strAll) {
        message.warning('等级有缺漏，请检查选择等级');
        return Promise.reject();
      }
      await addWarm({
        ...params,
        levelConfigDTOList,
        levelConfigVOList: undefined,
      });
      tableRef.value.refresh();
    },
  });
};
const onView = (record: any) => {
  openData.value = cloneDeep(record);
  open({
    title: (type) => (type === 'info' ? '详情' : '编辑'),
    modalType: 'info',
    defaultValue: openData.value,
    serviceApi: async (params: any): Promise<any> => {
      let arr: any = [];
      const levelConfigDTOList = cloneDeep(params.levelConfigVOList);
      levelConfigDTOList.forEach((list: any) => {
        arr = arr.concat(list.intensity);
        list.intensity = list.intensity?.join() || '';
      });
      if (arr.join() != strAll) {
        message.warning('等级有缺漏，请检查选择等级');
        return Promise.reject();
      }
      await updateWarm({
        ...params,
        levelConfigDTOList,
        levelConfigVOList: undefined,
      });
      tableRef.value.refresh();
    },
    hasEditPermission: hasPermission('levelConfig:edit'),
  });
};
const sleep = (cb) => {
  setTimeout(() => {
    cb();
  }, 500);
};
const onDelete = async () => {
  Modal.confirm({
    title: '系统提示',
    centered: true,
    content: `是否确认删除当前项？`,
    onOk: async () => {
      await deleteWarm(selectedRowKeys.value.join());
      sleep(() => tableRef.value.refresh());
      message.success('操作成功');
    },
  });
};
</script>
